/*
 * @Author: Zhang Wei
 * @Date: 2024-05-15 22:41:36
 * @LastEditors: Zhang Wei
 * @LastEditTime: 2024-05-27 23:01:06
 * @FilePath: \schulte-meter\miniprogram\pages\main\main.ts
 * @Description: 
 * @Word: There is nothing either good or bad, but thinking makes it so.
 */
/*===============  工具  ===============*/
import { GameRecord } from "@utils/GameRecord/GameRecord";
import Timer from "../../utils/Timer";
import dayjs from "dayjs";
import { clickSoundService, successSoundService } from '../../service/soundServices/index';

/*===============  接口  ===============*/

/*===============  页面  ===============*/

interface PageData {
  /** 页面尺寸 */
  size: number,

  /** 舒尔特表信息 */
  sMTableInfo: SMTableInfo

  /** 游戏状态 */
  gameStatus: IGameStatus

  showTimer: ITimer | undefined
}

let pageTimer: ITimer | null = null

const gameRecord = new GameRecord();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    size: 4,

    sMTableInfo: {
      data: [],
      nowClickItem: null,
      nextVal: 1,
    },

    gameStatus: 'undo',

    showTimer: undefined
  } as PageData,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    const _this = this;
    this.__initTableData();
    // this.__judgingGameOver();

    // @ts-ignore
    pageTimer = new Timer((nowTime: number, context: ITimer) => {
      _this.setData({
        showTimer: context
      })
    })

    this.setData({
      showTimer: pageTimer
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /*==============================================  逻辑  ==============================================*/

  /** 初始化表格数据 */
  __initTableData() {
    const { sMTableInfo } = this.data;

    sMTableInfo.data = this.__getShowArray();
    this.setData({
      sMTableInfo
    })

    console.log(`[this.data.sMTableInfo.data]`, this.data.sMTableInfo.data)
  },

  /** 生成舒尔特核心数据
   */
  __getShowArray(): SMDataLine[] {

    const { size } = this.data;

    const useSize = size * size;

    console.log(`[useSize]`, useSize, size)

    // 创建原始数组
    const list: SMDataItem[] = [];

    const colorList = [
      '#ffffff',
      '#ff8cd4',
      '#ffea64',
      '#7acefc'
    ]

    for (let index = 0; index < useSize; index++) {
      const mineItem: SMDataItem = {
        val: index + 1,
        coordinate: {
          x: index % size,
          y: Math.floor(index / size)
        },
        isClick: false,
        color: colorList[Math.floor(Math.random() * colorList.length)]
      }

      list.push(mineItem)
    }

    // 并打乱顺序
    list.sort(randomSort);

    console.log(`[list]`, list)

    const res: SMDataLine[] = [];
    let lineData: SMDataItem[] = [];
    list.map((item, index) => {
      // 重置坐标
      const mineCoordinate: Coordinate = {
        x: index % size,
        y: Math.floor(index / size)
      }

      item.coordinate = mineCoordinate;
      lineData.push(item);

      // console.log(`/*===============  start ${index}  ==============*/`)
      // console.log('[info]:', `[index]: ${index}`, size, index >= size, index % size === 0, `[test]: ${index >= size && index % size === 0}`)
      // console.log('[info]:', `[index]: ${index + 1}`, size, (index + 1) >= size, (index + 1) % size === 0, `[test]: ${index + 1 >= size && index + 1 % size === 0}`)
      // console.log(`/*===============  end ${index}  ==============*/`)

      if ((index + 1) >= size && (index + 1) % size === 0) {
        res.push(lineData)
        lineData = []
      }
    });

    return res

    /** 打乱排序 */
    function randomSort() {
      return Math.random() > .5 ? -1 : 1;//用Math.random()函数生成0~1之间的随机数与0.5比较，返回-1或1
    }
  },

  /** 判断游戏是否结束 */
  __judgingGameOver() {
    const _this = this;
    const { size, sMTableInfo: {
      nextVal
    } } = this.data;

    if (nextVal && (nextVal > size * size)) {
      this.gameOver();
      return false
    }

    return next();

    /** 进入下一轮判断 */
    function next() {
      setTimeout(() => {
        _this.__judgingGameOver()
      }, 100)
    }
  },

  /*==============================================  事件  ==============================================*/
  /**
   * 点击事件
   * @param cellItem 被点击的单元格
   */
  itemClick(e: { currentTarget: { dataset: { item: SMDataItem } } }) {
    let { item } = e.currentTarget.dataset;

    const { sMTableInfo } = this.data;
    const { nextVal } = sMTableInfo;

    console.log(item.val, nextVal)

    if (item.val === nextVal) {
      clickSoundService.play();

      sMTableInfo.nextVal = nextVal + 1;
      sMTableInfo.nowClickItem = item;

      this.setData({
        sMTableInfo
      })

      console.log(`[this.data]: `, this.data)
    }
  },

  /** 开始游戏 */
  startGame() {
    this.__initTableData();

    this.setData({
      gameStatus: 'running',
      [`sMTableInfo.nextVal`]: 1,
    });

    this.__judgingGameOver()

    console.log(`[startGame]`, this.data)
    pageTimer && pageTimer.start();
  },

  /** 保存游戏记录 */
  saveGameRecord() {
    const { showTimer, size } = this.data;

    const gameRecordItem: IGameRecordItem = {
      model: 'schulte-meter-base',
      gameLevel: `${size}x${size}`,
      score: 100,
      useTime: showTimer?.nowTime || 9999,
      gameDate: new Date().getTime().toString(),
      gameDateStr: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      openId: wx.getStorageSync('openId'),
    }

    gameRecord.saveDataNew(gameRecordItem)
  },

  /** 游戏结束 */
  gameOver() {
    const _this = this;

    const { showTimer } = this.data;

    successSoundService.play();

    this.saveGameRecord();

    wx.showModal({
      title: `游戏结束,用时 ${showTimer?.nowTime} 秒`,
      content: '是否重新开始游戏',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          _this.setData({
            gameStatus: 'undo'
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
          _this.setData({
            gameStatus: 'over'
          })
        }
      }
    });

    pageTimer && pageTimer.stop();
  },


  changeSize(e) {
    console.log(e);
    this.setData({
      size: e.detail.size
    })
  },
  /** 进入游戏记录界面 */
  toPageGameRecord() {
    wx.navigateTo({
      url: '../game-record/logs',
    })
  }
});
